package com.fengwk.user.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import com.fengwk.support.redis.RedisDatabase;
import com.fengwk.support.util.CodeUtils;
import com.fengwk.support.util.ObjectUtils;
import com.fengwk.user.service.RandomService;

@Service
public class RandomServiceImpl implements RandomService {

	private static final int DEFAULT_TIMEOUT_USERNAME = 60 * 2;
	private static final int DEFAULT_TIMEOUT_MOBILE_PHONE = 60 * 2;
	private static final int DEFAULT_TIMEOUT_EMAIL = 60 * 10;

	private static final String DEFAULT_TITLE = "减一科技";
	private static final String DEFAULT_TEMPLATE = "【减一科技】验证码:{{random}}";
	private static final String DEFAULT_TEMPLATE_REPLACE = "{{random}}";

	@Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String sender;
	
	@Autowired
	private RedisDatabase redisDatabase;

	@Override
	public String usernameRandom(String username) {
		return createRandom(username, DEFAULT_TIMEOUT_USERNAME);
	}

	@Override
	public void mobilePhoneRandom(String mobilePhone) {
		String random = createRandom(mobilePhone, DEFAULT_TIMEOUT_MOBILE_PHONE);
		// 发送手机验证码
		String template = DEFAULT_TEMPLATE.replace(DEFAULT_TEMPLATE_REPLACE, random);
		// ...
		System.out.println(template);
	}

	@Override
	public void emailRandom(String email) {
		String random = createRandom(email, DEFAULT_TIMEOUT_EMAIL);
		String title = DEFAULT_TITLE;
		String template = DEFAULT_TEMPLATE.replace(DEFAULT_TEMPLATE_REPLACE, random);
		SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sender);
        message.setTo(email);
        message.setSubject(title);
        message.setText(template);
        mailSender.send(message);
	}

	private String createRandom(String identity, int timeout) {
		String random = getRandom();
		redisDatabase.set(encodeRedisKey(identity), random, timeout);
		return random;
	}

	// 获取6位随机验证码
	private String getRandom() {
		return CodeUtils.random(6);
	}

	private String encodeRedisKey(String key) {
		return this.getClass().getName() + key;
	}

	@Override
	public boolean checkRandom(String identity, String random) {
		String getRandom = redisDatabase.get(encodeRedisKey(identity));
		return ObjectUtils.equals(getRandom, random);
	}

}
